<template>
  <BasicModal
    @register="register"
    title="编辑告警规则条件"
    @ok="save"
    :destroyOnClose="true"
    :body-style="{ marginLeft: '10px', marginRight: '10px' }"
    width="600px"
  >
    <Collapse expandIconPosition="right" :default-active-key="['1']" class="!mb-24px">
      <CollapsePanel header="键名筛选器" key="1">
        <Row>
          <Col span="9">键名</Col>
          <Col span="9">键类型</Col>
          <Col span="6" />
        </Row>
        <Divider class="!mb-20px !mt-2px" />
        <p class="text-center" v-show="condition.condition.length === 0">未配置键名筛选器</p>
        <Row v-for="(item, index) in condition.condition" :key="item.id" class="flex items-center">
          <Col span="9">{{ item[0].key.key }}</Col>
          <Col span="9">{{ item[0].key.type }}</Col>
          <Col span="6">
            <Button
              size="large"
              shape="circle"
              type="text"
              @click="toEdit(item, index)"
              v-show="!isDisable"
            >
              <Icon :icon="ICON.EDIT" />
            </Button>
            <Button
              size="large"
              shape="circle"
              type="text"
              @click="toEdit(item, index)"
              v-show="isDisable"
            >
              <Icon :icon="ICON.CHECK" />
            </Button>
            <Button
              size="large"
              shape="circle"
              type="text"
              @click="deleteCond(index)"
              v-show="!isDisable"
            >
              <Icon :icon="ICON.DELETE" />
            </Button>
          </Col>
        </Row>
        <Button type="primary" @click="toKeyNameFilter" v-show="!isDisable" class="mt-12px"
          >添加键名筛选器</Button
        >
      </CollapsePanel>
    </Collapse>

    <Collapse :default-active-key="['1']" expandIconPosition="right" class="!mb-24px">
      <CollapsePanel header="筛选器预览" key="1">
        <div v-show="condition.condition.length === 0">
          <span>未指定筛选器</span>
        </div>
        <div
          v-for="item in condition.condition"
          :key="item.id"
          class="flex items-center flex-row flex-wrap"
        >
          <ShowCondition :formData="item" :isFirst="true" />
        </div>
      </CollapsePanel>
    </Collapse>

    <span>条件类型</span>
    <Form :model="condition.spec" ref="formRef" layout="vertical">
      <Select
        class="!mb-24px !mt-12px !w-full"
        v-model:value="condition.spec.type"
        :disabled="isDisable"
      >
        <SelectOption value="SIMPLE">简单</SelectOption>
        <SelectOption value="DURATION">持续时间</SelectOption>
        <SelectOption value="REPEATING">重复</SelectOption>
      </Select>
      <div class="flex items-center flex-row justify-start">
        <FormItem
          :name="['predicate', 'defaultValue']"
          label="持续时间值"
          required
          v-if="condition.spec.type === 'DURATION' && TimeDynamic === false"
          class="w-full"
        >
          <InputNumber
            placeholder="持续时间值"
            v-model:value="condition.spec.predicate.defaultValue"
            :min="1"
            :max="2147483647"
            :parser="formatNumber"
            :disabled="isDisable"
          />
        </FormItem>
        <FormItem
          :name="['predicate', 'defaultValue']"
          label="事件计数值"
          required
          v-if="condition.spec.type === 'REPEATING' && TimeDynamic === false"
          class="w-full"
        >
          <InputNumber
            placeholder="事件计数值"
            v-if="condition.spec.type === 'REPEATING' && TimeDynamic === false"
            v-model:value="condition.spec.predicate.defaultValue"
            :min="1"
            :max="2147483647"
            :parser="formatNumber"
            :disabled="isDisable"
          />
        </FormItem>
        <FormItem label="动态源类型" class="!w-full" v-show="TimeDynamic === true">
          <Select
            v-model:value="condition.spec.predicate.dynamicValue.sourceType"
            placeholder="动态源类型"
            :disabled="isDisable"
            :allowClear="true"
          >
            <SelectOption value="CURRENT_TENANT">当前租户</SelectOption>
            <SelectOption value="CURRENT_CUSTOMER">当前客户</SelectOption>
            <SelectOption value="CURRENT_DEVICE">当前设备</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="属性源" class="!w-full" v-show="TimeDynamic === true">
          <Input
            placeholder="属性源"
            v-model:value="condition.spec.predicate.dynamicValue.sourceAttribute"
            :disabled="isDisable"
          />
        </FormItem>

        <Checkbox
          v-model:checked="condition.spec.predicate.dynamicValue.inherit"
          v-show="
            TimeDynamic === true &&
            (condition.spec.predicate.dynamicValue.sourceType === 'CURRENT_CUSTOMER' ||
              condition.spec.predicate.dynamicValue.sourceType === 'CURRENT_DEVICE')
          "
          :disabled="isDisable"
          ><span class="whitespace-nowrap">从所有者继承</span></Checkbox
        >
        <Button
          shape="circle"
          type="text"
          v-show="condition.spec.type != 'SIMPLE' && TimeDynamic === false"
          @click="showDynamic"
        >
          <Icon icon="heroicons:variable" />
        </Button>
        <Button
          shape="circle"
          type="text"
          v-show="condition.spec.type != 'SIMPLE' && TimeDynamic === true"
          @click="hidDynamic"
        >
          <Icon icon="bi:123" />
        </Button>
        <FormItem
          name="unit"
          label="时间单位"
          required
          v-if="condition.spec.type === 'DURATION'"
          class="!w-full"
        >
          <Select placeholder="时间单位" v-model:value="condition.spec.unit" :disabled="isDisable">
            <SelectOption value="SECONDS">秒</SelectOption>
            <SelectOption value="MINUTES">分钟</SelectOption>
            <SelectOption value="HOURS">小时</SelectOption>
            <SelectOption value="DAYS">天</SelectOption>
          </Select>
        </FormItem>
      </div>
    </Form>
  </BasicModal>
  <AddKeyNameFilterModel
    @register="registerKeyNameFilter"
    @push-out="receiveCondition"
    @edit="editCondition"
    :disable="isDisable"
  />
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useModal } from '/@/components/Modal';
  import { ref, watch } from 'vue';
  import {
    Row,
    Col,
    Select,
    SelectOption,
    InputNumber,
    Input,
    Checkbox,
    Collapse,
    CollapsePanel,
    Divider,
    Form,
    FormItem,
    Button,
  } from 'ant-design-vue';
  import Icon from '/@/components/Icon';
  import { ICON } from '/@/enums/iconEnum';
  import AddKeyNameFilterModel from './AddKeyNameFilterModel.vue';
  import ShowCondition from './ShowCondition.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  const emit = defineEmits(['get-data']);
  const props = defineProps({
    disable: { type: Boolean },
  });
  let isDisable = ref<boolean>(false);
  let formRef = ref<any>(null);
  //所有条件
  let condition = ref<any>({
    condition: [],
    spec: {
      type: 'SIMPLE',
      unit: 'SECONDS',
      predicate: {
        defaultValue: null,
        dynamicValue: {
          inherit: false,
          sourceAttribute: '',
          sourceType: null,
        },
      },
    },
  });
  //记录修改的是哪一个条件
  let whoEdit = ref<any>();
  //控制下方配置动态值是否显示
  let TimeDynamic = ref<boolean>(false);
  const { createMessage } = useMessage();
  watch(
    () => props.disable,
    (nVal) => {
      isDisable.value = nVal;
    },
    { immediate: true },
  );
  const [register, { closeModal }] = useModalInner((data) => {
    if (data) {
      Object.assign(condition.value.spec, data.spec);
      condition.value.condition = data.condition;
    }
  });
  const [registerKeyNameFilter, { openModal: openKeyNameFilter }] = useModal();

  //添加条件
  function receiveCondition(data: Recordable) {
    condition.value.condition.push(data);
  }
  //修改条件
  function editCondition(data: Recordable) {
    condition.value.condition[whoEdit.value] = data;
  }
  //删除条件
  function deleteCond(index: number) {
    condition.value.condition.splice(index, 1);
  }
  //去打开修改条件弹窗
  function toEdit(data: Recordable, index: number) {
    whoEdit.value = index;
    openKeyNameFilter(true, data);
  }
  //打开键名筛选器弹窗
  function toKeyNameFilter() {
    openKeyNameFilter(true);
  }
  //显示动态值配置
  function showDynamic() {
    TimeDynamic.value = true;
  }
  //隐藏动态值配置
  function hidDynamic() {
    TimeDynamic.value = false;
  }

  function formatNumber(text: string) {
    const decimalIndex = text.indexOf('.');
    return /^\d+$/.test(text) ? text : text.slice(0, decimalIndex);
  }
  async function save() {
    try {
      await formRef.value.validate();
    } catch (e) {
      createMessage.error('必填项为空');
      return null;
    }
    emit('get-data', condition.value);

    condition.value = {
      condition: [],
      spec: {
        type: 'SIMPLE',
        unit: null,
        predicate: {
          defaultValue: null,
          dynamicValue: {
            inherit: false,
            sourceAttribute: '',
            sourceType: null,
          },
        },
      },
    };
    closeModal();
  }
</script>
